package org.nf.db.util.result;

import org.nf.db.util.ResultSetHandler;
import org.nf.db.util.RowProcessor;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author wangl
 * @date 2021/7/28
 */
public class ColumnHandler<T> implements ResultSetHandler<T> {

    /**
     * 要获取列的下标
     */
    private int columnIndex;
    /**
     * 列名
     */
    private String columnName;


    public ColumnHandler(int columnIndex) {
        this.columnIndex = columnIndex;
    }

    public ColumnHandler(String columnName) {
        this.columnName = columnName;
    }

    /**
     * 根据下标 or 列名 获取值
     * @param rs 结果集
     * @return 返回 下标 or 列名
     * @throws SQLException 异常
     */
    @SuppressWarnings("unchecked")
    @Override
    public T handle(ResultSet rs) throws SQLException {
        if(rs.next()) {
            if(this.columnName == null) {
                return (T) RowProcessor.toValue(rs, this.columnIndex);
            }
            return (T) RowProcessor.toValue(rs, this.columnName);
        }
        return null;
    }
}
